<template>
  <el-dialog title="批量修改" v-model="show" width="800px" @close="closeModal">
    <el-form ref="formRef" :model="form" label-width="80px" v-loading="loading" :element-loading-text="`正在更新中`">
      <el-form-item prop="SeriesId" required label="产品类型"
        :rules="[{ required: true, message: '请选择产品类型', trigger: 'change' }]">
        <el-select v-model="form.SeriesId" placeholder="请选择类型" :multiple="true" @change="getAttrs(form.SeriesId)">
          <!-- <template #header v-if="form.SeriesId.length">
            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
              全部
            </el-checkbox>
          </template> -->
          <el-option v-for="item in series" :label="item.SeriesName" :value="item.SeriesId"
            :key="item.SeriesId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择属性">
        <el-select v-model="selectAttrs" collapse-tags collapse-tags-tooltip :max-collapse-tags="100" filterable
          placeholder="请选择属性" multiple @change="handleSelect">
          <template #header v-if="attrs.length">
            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
              全部
            </el-checkbox>
          </template>
          <el-option v-for="item in attrs" :key="item.AttrId" :label="item.AttrName" :value="item.AttrId">
          </el-option>
        </el-select>
        <div v-if="attrs.length > 0">
          <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll" border
            style="margin: 2px">
            全部
          </el-checkbox>
          <div>
            <el-checkbox v-for="item in attrs" :key="item.AttrId" v-model="item.checked" :label="item.AttrName"
              style="margin: 2px" border @change="(val) => handleChecked(val, item.AttrId)" />
          </div>
        </div>
        <div v-else class="mx-auto translate-x-[-20%]">
          <el-empty :description="form.SeriesId ? '该类型下暂无属性数据' : '请先选择产品类型'
            "></el-empty>
        </div>
      </el-form-item>
      <el-form-item prop="ColumnWidth" label="列宽度">
        <el-input v-model="form.ColumnWidth" class="w-1/4" placeholder="请输入列宽度"></el-input>
      </el-form-item>
      <el-form-item prop="DefaultValue" label="默认值">
        <el-input v-model="form.DefaultValue" class="w-1/4" placeholder="请输入默认值"></el-input>
      </el-form-item>
      <el-form-item prop="InputType" label="输入方式">
        <el-select v-model="form.InputType" class="w-1/4" clearable>
          <el-option v-for="(item, key) in inputTypeMap" :key="key" :label="item" :value="Number(key)">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="FixType" label="列固定">
        <el-select v-model="form.FixType" class="w-1/4" clearable>
          <el-option v-for="(item, key) in fixMap" :key="key" :label="item.label" :value="Number(key)">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.IsVisible" class="w-1/4" clearable>
          <el-option label="显示" :value="true"> </el-option>
          <el-option label="隐藏" :value="false"> </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="loading" @click="closeModal">取消</el-button>
        <el-button type="primary" :disabled="loading" @click="handleConfirm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { watch } from "vue";
import {
  inputTypeMap,
  inputModeMap,
  orderAttrsMap,
  fixMap,
} from "../../../../../utils/map";
import {
  attrQueryApi,
  attrUpdateApi,
  attrRemoveApi,
} from "@/api/order/attr/index.js";
import { seriesQueryApi } from "@/api/order/series/index.js";
import { ElMessage } from "element-plus";

const props = defineProps({
  open: {
    type: Boolean,
    required: true,
  },
});
const emits = defineEmits(["reload", "closeModal"]);
const show = ref(false);
const attrs = ref([]);
const series = ref([]);
const checkAll = ref(false);
const loading = ref(false);
const loadingNum = ref(0);
const indeterminate = ref(false);
const selectAttrs = ref([]);
const form = ref({
  FixType: null,
  InputType: null,
  IsVisible: null,
  ColumnWidth: null,
  DefaultValue: null,
});
const rules = ref({
  ColumnWidth: [{ message: "请输入列宽度", required: true }],
  FixType: [{ message: "请选择列固定", required: true }],
  SeriesId: [{ message: "请选择产品类型", required: true }],
});
watch(
  () => props.open,
  (openVal) => {
    show.value = openVal;
    getSeries();
  }
);
watch(
  () => selectAttrs.value,
  (val) => {
    let total = attrs.value.length;
    let selected = attrs.value.filter((s) => s.checked).length;
    if (selected > 0 && selected < total) {
      indeterminate.value = true;
    } else {
      indeterminate.value = false;
    }
  },
  {
    deep: true,
  }
);
async function handleConfirm() {
  loading.value = true;
  try {

    for (let j = 0; j < form.value.SeriesId.length; j++) {
      for (let i = 0; i < selectAttrs.value.length; i++) {
        loadingNum.value = i + 1;
        for (let key in form.value) {
          if (form.value[key] == null) delete form.value[key];
        }
        // 如果不是第一个选择的系列，AttrId要变
        let attr = attrs.value.find((a) => a.AttrId == selectAttrs.value[i])
        let attrId = attr.AttrId
        if (form.value.SeriesId[j] !== attr.SeriesId) {
          const res = await attrQueryApi({ seriesId: form.value.SeriesId[j], keyStr: attr.AttrName, pageSize: 100 });
          if (res.Data.length == 0) {
            ElMessageBox.confirm(`新增失败，${form.value.SeriesId[j]}不存在${attr.AttrName}属性`, '错误', {
              type: 'error'
            })
            throw new Error()
          } else {
            attrId = res.Data[0].AttrId
          }
        }
        await attrUpdateApi({
          ...attr,
          ...form.value,
          AttrId: attrId,
          SeriesId: form.value.SeriesId[j],
        });
      }
    }
    ElMessage.success("修改成功");
    emits("reload");
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false;
  }
}
function closeModal() {
  show.value = false;
  emits("closeModal");
}
async function getAttrs(seriesId) {
  const res = await attrQueryApi({ seriesId: seriesId[0], pageSize: 100 });
  attrs.value = res.Data || [];
  attrs.value.forEach((item) => {
    item.checked = false;
  });
}
async function getSeries() {
  const res2 = await seriesQueryApi();
  series.value = res2.Data;
}
function handleSelect(val) {
  val.forEach((id) => {
    attrs.value.find((a) => a.AttrId == id).checked = true;
  });
}
function handleChecked(val, AttrId) {
  if (val) selectAttrs.value.push(AttrId);
  else selectAttrs.value = selectAttrs.value.filter((id) => id !== AttrId);
}
function handleCheckAll(val) {
  indeterminate.value = false;
  if (val) {
    attrs.value.forEach((item) => {
      item.checked = true;
    });
    selectAttrs.value = attrs.value.map((a) => a.AttrId);
  } else {
    attrs.value.forEach((item) => {
      item.checked = false;
    });
    selectAttrs.value = [];
  }
}
</script>
